﻿using Microsoft.Office.Interop.Excel;
using SUNRPA.CONTROLS.IMPL.domain;
using SUNRPA.CONTROLS.IMPL.domain.flowItemParam;
using SUNRPA.CONTROLS.IMPL.domain.flowRunningVar;
using SUNRPA.CONTROLS.IMPL.util;
using System.Collections.Concurrent;

namespace SUNRPA.CONTROLS.IMPL.controls {
    public class CloseExcelNAction:BaseControlActions {
        public override int Execute(int currentIndex, FlowItem item, ConcurrentDictionary<string, ConcurrentDictionary<string, RPAVariableDefineWrapper>> globleData, List<FlowItem> flowItems) {
            CloseExcelNParam? param = item.ControlParam as CloseExcelNParam;
            int closeOper = param.CloseOper;
            int beforeClose = param.BeforeClose;
            ExcelUtil excelUtil = new ExcelUtil();
            if(closeOper == 0) {
                //关闭指定
                string closeName = param.CloseObjName;
                Workbook wb = this.GetObjVar<ExcelModel>(ref closeName, globleData).WorkBookValue as Workbook;
                if(wb == null) { 
                    throw new RpaRuntimeException("未找到对象{}" + closeName);
                }
                excelUtil.SetApp(wb);
                if(beforeClose == 0) { 
                    //保存
                    excelUtil.SaveWorkBook();
                }else if(beforeClose == 1){
                    //另存为
                    string saveAsPath = param.SaveAsPath;
                    this.GetStringVar(ref saveAsPath, globleData);
                    excelUtil.WorkBookSaveAs(saveAsPath, param.CoverIfExist);
                }
                excelUtil.CloseCurrentExcel();
            } else { 
                //关闭全部
                ExcelUtil.CloseAllExcel();
            }
            return currentIndex;
        }
        
    }
}
